﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace CarRental.Control.User
{
    using CarRental.Database;

    public partial class CarsListGrid : System.Web.UI.UserControl
    {
        private DataTable dataSource { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.dataSource = this.GetCarsForGridView();

            if (!IsPostBack)
            {
                BindGrid();
            }
        }

        private void BindGrid()
        {
            CarsGridView.DataSource = this.dataSource;
            CarsGridView.DataBind();
        }

        private DataTable GetCarsForGridView()
        {
            var cars = Database.GetCars();

            DataTable dataTable = new DataTable();

            // - Dodanie definicji kolumn -

            dataTable.Columns.Add(new DataColumn("Id", typeof(int)));
            dataTable.Columns.Add(new DataColumn("RegistrationNumber", typeof(string)));
            dataTable.Columns.Add(new DataColumn("Producer", typeof(string)));
            dataTable.Columns.Add(new DataColumn("Model", typeof(string)));
            dataTable.Columns.Add(new DataColumn("ProductionYear", typeof(DateTime)));
            dataTable.Columns.Add(new DataColumn("AddDate", typeof(DateTime)));
            dataTable.Columns.Add(new DataColumn("IsActive", typeof(bool)));

            foreach (var row in cars)
            {
                DataRow dataRow = dataTable.NewRow();

                dataRow["Id"] = row.Id;
                dataRow["RegistrationNumber"] = row.RegistrationNumber;
                dataRow["Producer"] = row.ProducerName;
                dataRow["Model"] = row.ModelName;
                dataRow["ProductionYear"] = row.ProductionYear;
                dataRow["AddDate"] = row.AddDate;
                dataRow["IsActive"] = row.IsActive;
                
                dataTable.Rows.Add(dataRow);
            }

            return dataTable;
        }

        protected void RowCommandHandler(object sender, GridViewCommandEventArgs e)
        {
            string command = e.CommandName;
            int carId = Int32.Parse(e.CommandArgument.ToString());

            switch (command)
            {
                case "EditCar":
                    Response.Redirect("/Admin/CarEdit.aspx?id=" + carId);
                    break;

                default:
                    break;
            }
        }

    }
}